<?php
namespace Shopmobile\Model;
use Think\Model;
class MissionModel{
	public $sid;
	public $eid;
	public $shop_uid;
	public $mission;
	public $msg;
	public $usernick;
	public $mixednick;
	public $do_jifen_exchange;
	public $jifen_setting;
	public $jifen;
	public $jifen_gift;
	public $jifen_cfg;
	public $cart_items;
	public $cart_cfg;
	public $signCurrentDate; //当前的签到日期，用于读取当月的签到日历信息
	public $signList; //获取的签到日期
	public $gid; //连续签到兑换的奖品ID
	public function doMission(){
		switch($this->mission){
			case "everyday" :
				$this->getEveryday();
			break;
			case "sign" :
				$this->jifenSetting();
				if(!$this->jifen_cfg){
					$this->hasError=true;
					$this->msg = "尚未配置积分功能";
					return;
				}
				$this->getSignList();
			break;
			case "order" :
				return $this->orderExcange();
			break;
			case "jifen" :
				if($this->do_jifen_exchange){
					$this->jifenSetting();
					$this->jifenExcange();
				}else{
					$this->jifenSetting();
					$this->hasError=true;
					$this->msg = "请选择要兑换的积分";
				}
			break;
			case "cartadd" :
				$this->cartSetting();
			break;
			case "cartadd_check" :
				$this->cartCheck();
			break;
			case "get_sign_gift":
				$this->jifenSetting();
				if(!$this->jifen_cfg){
					$this->hasError=true;
					$this->msg = "尚未配置积分功能";
					return;
				}
				if(!$this->jifen_cfg["onoff_qddh"]){
					$this->hasError = true;
					$this->msg = "抱歉，签到兑换已关闭";
					return;
				}
				$this->getSignGift();
			break;
		}
	}
	private function getSignGift(){
		
		$Seeds = D("Shopmodule/User");
		$Seeds->suid = $this->shop_uid;
		$Seeds->sid = $this->sid;
		$Seeds->curdate = $this->signCurrentDate?$this->signCurrentDate:date("Y-m-d");
		$Seeds->rili();
		$this->signList = $Seeds->signlist;

		$isok = false;
		foreach($this->signList as $list){
			if($list["date"]==date("Y-m-d",strtotime($this->signCurrentDate)) && ($list["signType"]==1||$list["signType"]==4) ){
				$isok = true;
				$gid = $list["giftId"];
				$qdinfo = $list;
			}
		}
		$msg = $isok?"允许兑换。":"亲，您需要签到才可以领取奖品哦！";
		if(!$isok){
			$this->hasError=true;
			$this->msg = $msg;
			return;
		}
		$DHINF = M("SeedsQddh");
		$dhid = $DHINF->where("`sid`=".$this->sid." AND `suid`=".$this->shop_uid." AND DATE_FORMAT(`qd_date`,'%Y-%m-%d')='".$qdinfo["date"]."'")->getField("`id`");
		if($dhid){
			$this->hasError=true;
			$this->msg = "亲，您已经兑换过这天的奖品啦，请不要重复兑换哦！";
			return;
		}
		
		//此处为用户增加奖品
		$GFT = M("Gifts");
		$gift = current($GFT->where(Array("id"=>$gid,"sid"=>$this->sid))->getField("id AS gift_id,quantity,name,pic_url,type"));
		if($gift["quantity"]<=0){
			$this->hasError=true;
			$this->msg = "抱歉！这个奖品已经被领完了";
			return;
		}
		
		$UGFT = M("UsersGifts");
		$ugft["sid"]=$this->sid;
		// $ugft["eventid"]=$this->eid; //这不是活动中的奖品。默认为0。如果传入，会提示“没有这个奖品”。
		$ugft["sys_giftid"]=$gid;
		$ugft["uzuid"]=$this->shop_uid;
		$ugft["giftid"]=$gid;
		$ugft["gtype"]=$gift["type"];
		$ugft["gift_name"]=$gift["name"];
		$ugft["gift_pic_url"]=$gift["pic_url"];
		$ugft["actiontime"]=date("Y-m-d H:i:s");
		$ugft["picup_time"]=date("Y-m-d H:i:s");
		$ugft["is_picup"]=1; //此处直接发放权益
		$ugid = $UGFT->add($ugft);
		if($ugid === false){
			$this->hasError=true;
			$this->msg = "抱歉！领奖失败。";
			return;
		}else{
			//处理权益获取流程
			$GFTR = D("GiftRights");
			$GFTR->gift = $gift;
			$GFTR->sid = $this->sid;
			$GFTR->eid = $this->eid;
			$GFTR->shop_uid = $this->shop_uid;
			$GFTR->sendGiftRights();
			if(!$GFTR->hasError){
				// 没有出错的情况下奖品数量减1
				$GFT->where(Array("id"=>$gid,"sid"=>$this->sid))->setDec("quantity");
			}
		}
		// 增加兑换记录
		$data = Array();
		$data["sid"]=$this->sid;
		$data["gift_id"]=$gid;
		$data["user_nick"]=$this->usernick;
		$data["mixednick"]=$this->mixednick;
		$data["suid"]=$this->shop_uid;
		// $data["user_gift_id"]=$UG->status["ugid"];//用户的奖品id
		$data["user_gift_id"]=$ugid;//用户的奖品id
		$data["qd_date"]=$qdinfo["date"];
		$data["get_time"]=date("Y-m-d H:i:s");
		$re = $DHINF->add($data);
		
		if($re===false){
			$this->hasError=true;
			$this->msg="失败！".$GFTR->msg;
		}else{
			$this->hasError=false;
			$this->msg="领取奖品".$gift['name']."成功！".$GFTR->msg;
		}
	}
	public function getSignList(){
		$Seeds = D("Shopmodule/User");
		$Seeds->suid = $this->shop_uid;
		$Seeds->sid = $this->sid;
		$Seeds->curdate = $this->signCurrentDate?$this->signCurrentDate:date("Y-m-d");
		$Seeds->rili();
		$this->signList = $Seeds->signlist;
		// 这里要给出signList
		// $this->signList=json_decode('[{"signDay":29,"signType":1},{"signDay":2,"signType":2},{"signDay":10,"signType":3},{"signDay":4,"signType":4},{"signDay":5,"signType":5},{"signDay":6,"signType":6},{"signDay":7,"signType":7},{"signDay":8,"signType":2,"giftDay":1}]');
		// $this->hasError=true;
		// $this->msg = "等待开发".json_encode($this->jifen_cfg);
	}
	
	// 不验证是否加入购物车，直接给予机会
	private function cartCheck(){
		$ITEM = M("EventsUsersCartItems");
		$iwh=Array("sid"=>$this->sid,"user_id"=>$this->shop_uid,"eid"=>$this->eid,"item_id"=>$this->iid);
		$status = $ITEM->where($iwh)->getField("status");

		if($status==1)
		{
			$this->hasError=true;
			$this->code="hasdone";
			$this->msg = "您已获取过这个商品的抽奖机会";
			return;
		}
		$EV = M("Events");
		$cfg = current($EV->where(Array("id"=>$this->eid,"sid"=>$this->sid))->getField("id,tms_cartadd,tms_cartadd_limit"));
		
		$iwh=Array("sid"=>$this->sid,"user_id"=>$this->shop_uid,"eid"=>$this->eid,"status"=>1);
		$all_scores = $ITEM->where($iwh)->getField("id,score");
		
		if(array_sum($all_scores)>=$cfg["tms_cartadd_limit"])
		{
			$this->hasError=true;
			$this->code="limit";
			$this->msg = "可获得的抽奖机会已达到上限";
			return;
		}
		
		// $sa["id"]=key($item);
		$sa["sid"]=$this->sid;
		$sa["user_id"]=$this->shop_uid;
		$sa["eid"]=$this->eid;
		$sa["score"]=$cfg["tms_cartadd"];
		$sa["item_id"]=$this->iid;
		$sa["sku_id"]=0;
		$sa["seller_nick"]=0;
		$sa["mix_buyer_nick"]=$this->mixednick;
		$sa["trace_id"]=time(); //加购唯一ID
		$sa["isv_ext"]="no_check".time();//isv唯一ID
		$sa["status"]=1;
		$sa["add_time"]=date("Y-m-d H:i:s");
		$ITEM->add($sa);
		
		$EU = M("EventsUsers");
		$EU->where(Array("uzuid"=>$this->shop_uid,"eventid"=>$this->eid,"sid"=>$this->sid))
		   ->setInc("score",$cfg["tms_cartadd"]);
		
		$this->hasError=false;
		$this->code="success";
		$this->get_score=$cfg["tms_cartadd"];
		$this->msg = "加购成功，您已获取".$cfg["tms_cartadd"]."次抽奖机会！";
	}
	//通过SPI确认加购
	private function cartCheckByIsvExt(){
		$ITEM = M("EventsUsersCartItems");
		$iwh=Array("sid"=>$this->sid,"user_id"=>$this->shop_uid,"eid"=>$this->eid,"item_id"=>$this->iid);
		$status = (S(implode($iwh))==1)?1:$ITEM->where($iwh)->getField("status");

		if($status==1)
		{
			S(implode($iwh),$status);
			$this->hasError=true;
			$this->code="hasdone";
			$this->msg = "您已获取过这个商品的抽奖机会";
			return;
		}
		$item = $ITEM->where(Array("isv_ext"=>$this->isv_ext))->getField("id,item_id");
		// if($this->mixednick == $item["mix_buyer_nick"] && $this->iid == $item["item_id"]){
		if($item && $this->iid == current($item))
		{
			$EV = M("Events");
			$cfg = current($EV->where(Array("id"=>$this->eid,"sid"=>$this->sid))->getField("id,tms_cartadd,tms_cartadd_limit"));
			
			$iwh=Array("sid"=>$this->sid,"user_id"=>$this->shop_uid,"eid"=>$this->eid,"status"=>1);
			$all_scores = $ITEM->where($iwh)->getField("id,score");
			
			if(array_sum($all_scores)>=$cfg["tms_cartadd_limit"])
			{
				$this->hasError=true;
				$this->code="limit";
				$this->msg = "可获得的抽奖机会已达到上限";
				return;
			}
			
			$sa["id"]=key($item);
			$sa["sid"]=$this->sid;
			$sa["user_id"]=$this->shop_uid;
			$sa["eid"]=$this->eid;
			$sa["score"]=$cfg["tms_cartadd"];
			$sa["status"]=1;
			$ITEM->save($sa);
			
			$EU = M("EventsUsers");
			$EU->where(Array("uzuid"=>$this->shop_uid,"eventid"=>$this->eid,"sid"=>$this->sid))
			   ->setInc("score",$cfg["tms_cartadd"]);
			
			$this->hasError=false;
			$this->code="success";
			$this->get_score = $cfg["tms_cartadd"];
			$this->msg = "加购成功，您已获取".$cfg["tms_cartadd"]."次抽奖机会！";
		}else{
			$this->hasError=true;
			$this->code="waitting";
			$this->msg = "等待购物车返回数据";
		}
	}
	private function cartSetting(){
		$EV = M("Events");
		$this->cart_cfg = current($EV->where(Array("id"=>$this->eid,"sid"=>$this->sid))->getField("id,tms_cartadd,tms_cartadd_limit"));
		$EV = M("Events");
		$items = $EV->where(Array("id"=>$this->eid))->getField("cart_items");
		if(TAE){
			$this->cart_items = (json_decode(urldecode_utf8($items)));
		}else{
			$this->cart_items = (json_decode(urldecode($items)));
		}
	}
	private function jifenSetting(){
		$TOOL = M("ToolsStatus");
		$this->jifen_cfg = json_decode($TOOL->where(Array("sid"=>$this->sid,"tool_id"=>13))->getField("cfg"),true);
		$this->jifen_setting=Array("dh"=>$this->jifen_cfg["dh"],"onoff_jfdh"=>$this->jifen_cfg["onoff_jfdh"]);
	}
	private function jifenExcange(){
		if($this->jifen_setting["onoff_jfdh"]==1){
			foreach($this->jifen_setting["dh"] as $dh){
				if($dh["gift"]==$this->jifen_gift && $dh["jifen"]==$this->jifen){
					$target=$dh;
					$do_exchange = true;
				}
			}
			if($do_exchange){
				$USR = M("ShopUsers");
				$seeds = $USR->where(Array("id"=>$this->shop_uid))->getField("seeds");
				if($seeds>=$target["jifen"]){
					$GFT = M("Gifts");
					$gift = current($GFT->where(Array("id"=>$this->jifen_gift))->getField("id,zailai,quantity,type"));
					if($gift["quantity"]>0){
						if($gift["type"]==7){
							$score_add = $gift["zailai"];
							$EUR = M("EventsUsers");
							$EUR->where(Array("sid"=>$this->sid,"eventid"=>$this->eid,"uzuid"=>$this->shop_uid))->setInc("score",$score_add);
							$USR->where(Array("id"=>$this->shop_uid))->setDec("seeds",$target["jifen"]);
							$GFT->where(Array("id"=>$this->jifen_gift))->setDec("quantity");
							$this->hasError=false;
							$this->get_score = $score_add;
							$this->msg = "您已成功兑换 $score_add 次抽奖机会";
						}else{
							$this->hasError=true;
							$this->msg = "暂不支持兑换这个奖品类型";
						}
					}else{
						$this->hasError=true;
						$this->msg = "兑换总数超出限制";
					}
				}else{
					$this->hasError=true;
					$this->msg = "您的积分不足。";
				}
			}else{
				$this->hasError=true;
				$this->msg = "抱歉，没有这个兑换选项。";
			}
		}else{
			$this->hasError=true;
			$this->msg = "抱歉，积分兑换已关闭。";
		}
	}
	private function orderExcange(){
		//此处仅用于兑换抽奖次数。
		//兑换奖品使用Shopmobile/Gifts->pickup()
		if(!is_numeric($this->oid)){
			$this->hasError=true;
			$this->msg="订单号有误！请重新输入";
			return;
		}
		
		$CFG = M("ShopCfg");
		$sessionkey = $CFG->where(Array("sid"=>$this->sid))->getField("sessionkey");
			
		if(C("TAE")){
			Vendor('taobaosdk.top.TopClient');
		}else{
			Vendor('taobaosdk.top.TopClient');
		}
		Vendor('taobaosdk.lotusphp_runtime.Logger.Logger');
		Vendor('taobaosdk.top.RequestCheckUtil');
		Vendor('taobaosdk.top.request.TradeGetRequest');
		$this->c =  new \TopClient();
		$this->c->appkey=C("SM_KEY");
		$this->c->secretKey=C("SM_SECRET");
		$this->c->format="xml";
		
		// 这个新表不见了，以下逻辑仍然使用旧表
		// $ORD = M("EventsUserOrder");
		// $add_time = $ORD->where(Array("oid"=>$this->oid))->getField("add_time");
		// if($add_time)
		// {
			// $this->hasError=true;
			// $this->msg="您已于".$add_time."兑换过这个订单。";
			// return;
		// }
			$EV = M("Events");
			$fields = "`id`,`orderset`,`order_payment`, `order_payment_addon`, `order_pay_time_start`, `order_pay_time_end`, `order_items`, `order_success_times`,`tms_goodrate`,`order_pay_times`";
			$shopcfg = current($EV->where(Array("id"=>$this->eid,"sid"=>$this->sid))->getField($fields));
			// print_r($orderset);
			if($shopcfg["orderset"]==0){
				$reda["hasError"]=true;$reda["status"]=false;
				$reda["score"]=0;
				$reda["giftname"]="抱歉，订单兑换已经关闭！";
				return $reda;
			}
				
			$Order = M("Orders");
			$topic = current($Order->where("`oid`=".$this->oid)->getField("id,topic,status,payment,buyer_nick,exchange_byuser"));//echo $Order->_sql();

			if($topic)
			{ // 已保存订单号逻辑
				$save = true;
				
				/*
				$mixed = S("mixed".$topic["buyer_nick"]); //读取缓存的混淆昵称
				if(!$mixed){
					// 订单中的昵称转化为混淆昵称
					Vendor('taobaosdk.top.request.MixnickGetRequest');
					$this->c->appkey=C("FT_KEY");
					$this->c->secretKey=C("FT_SECRET");
					$req = new \MixnickGetRequest;
					$req->setNick($topic["buyer_nick"]);
					$mixed = $this->c->execute($req);
					$mixed = $mixed->nick;
					S("mixed".$topic["buyer_nick"],(string)$mixed);
				}
				
				if($this->mixednick!=$mixed){
					$reda["hasError"]=true;$reda["status"]=false;
					$reda["score"]=0;
					$reda["giftname"]="抱歉，该订单号不是你的哦！请换一个吧！";
					return $reda;
				}
				// 增加一个字段exchange_byuser，不再判断订单号是否本人，效果有待观察。
				*/
				if($topic["exchange_byuser"]!=$this->mixednick){
					$reda["hasError"]=true;$reda["status"]=false;
					$reda["score"]=0;
					$reda["giftname"]="抱歉，这个订单号已经被".substr($this->mixednick,0,1)."***兑换过了";
					return $reda;
				}
				
				if($shopcfg["order_payment"]>0){
					$bei = (int)($topic["payment"]/$shopcfg["order_payment"]);
					$bei = $shopcfg["order_payment_addon"]>$bei?$bei:$shopcfg["order_payment_addon"];
					// 超额倍数
				}
				
				if($topic["payment"]<$shopcfg["order_payment"]){
					$reda["hasError"]=true;$reda["status"]=false;
					$reda["score"]=0;
					$reda["giftname"]="抱歉，".$shopcfg["order_payment"]."元以上的订单才可以兑换。";
					if($shopcfg["andor"]!=1){
						return $reda;
					}
				}
				if($topic["status"]==4){
					$reda["hasError"]=true;$reda["status"]=false;
					$reda["score"]=0;
					$reda["giftname"]="这个订单已经兑换过了。";
					return $reda;
				}
				if($topic["status"]==3 && $shopcfg["tms_goodrate"]<=0)
				{
					//收货后抽奖已抽过，要判断是否存在好评抽奖
					$reda["hasError"]=true;$reda["status"]=false;
					$reda["score"]=0;
					$reda["giftname"]="这个订单已经收货兑换过了。";
					return $reda;
				
				}
				if($topic["status"]==2 &&  $shopcfg["order_success_times"]<=0 && $shopcfg["tms_goodrate"]<=0)
				{
					// 付款后抽奖已抽过，要判断是否存在收货后抽奖、好评抽奖
					$reda["hasError"]=true;$reda["status"]=false;
					$reda["score"]=0;
					$reda["giftname"]="这个订单已经付款兑换过了。";
					return $reda;
					
				}
				if($topic["status"]<2 && $shopcfg["order_payment"]<=0 && $shopcfg["order_success_times"]<=0 && $shopcfg["tms_goodrate"]<=0)
				{
					// 根本没抽过，要判断是否有付款后抽奖、收货抽奖、好评抽奖
					$reda["hasError"]=true;$reda["status"]=false;
					$reda["score"]=0;
					$reda["giftname"]="这个订单已经兑换过了。";
					return $reda;
				}
				
			}
			// 以上都不成立，进入读取订单数据环节
				$req = new \TradeGetRequest;
				$req->setFields("buyer_nick,seller_nick,payment,orders.num_iid,price,num,buyer_rate,status,pay_time,end_time");
				$req->setTid($this->oid);
				$resp = $this->c->execute($req, $sessionkey);
				// print_r($resp);1858928659855505
				if($resp->code)
				{
					$reda["hasError"]=true;
					$reda["hasError"]=true;$reda["status"]=false;
					$reda["giftname"]="读取订单出错！请联系客服，错误码：<br />".$resp->msg."<br />".$resp->sub_msg;
					return $reda;
				}
				
				if($shopcfg["order_payment"]>0)
				{
					$bei = (int)($resp->trade->payment/$shopcfg["order_payment"]);
					$bei = $shopcfg["order_payment_addon"]>$bei?$bei:$shopcfg["order_payment_addon"];
					// 超额倍数
				}
				if(!$resp->trade->status)
				{
					$reda["hasError"]=true;
					$reda["hasError"]=true;$reda["status"]=false;
					$reda["score"]=0;
					$reda["giftname"]="抱歉，没找到该订单。亲，3个月以内的订单号才可以哦！";
					return $reda;
				}
				if((float)$resp->trade->payment<$shopcfg["order_payment"])
				{
					$reda["hasError"]=true;$reda["status"]=false;
					$reda["score"]=0;
					$reda["giftname"]="抱歉，".$shopcfg["order_payment"]."元以上的订单才可以抽奖。";
					if($shopcfg["andor"]!=1){
						return $reda;
					}
				}else{
					$trade_rule[] = "payment";
				}
					
				if($shopcfg["order_items"])
				{
					if(C("TAE")){
						$orderitems = (json_decode(urldecode_utf8($shopcfg["order_items"])));
					}else{
						$orderitems = (json_decode(urldecode($shopcfg["order_items"])));
					}
					// $orderitems = explode(",",$shopcfg["order_items"]);
					$hasitem = false;
					foreach($resp->trade->orders->order as $order){
						foreach($orderitems as $item){
							if($order->num_iid == $item[0]){
								$hasitem=true;
							}
						} 
					}
					if(!$hasitem){
						$reda["hasError"]=true;$reda["status"]=false;
						$reda["score"]="0";
						$reda["giftname"]="亲，只有购买指定商品才可以抽奖哦！请仔细查看抽奖规则。";
						$reda["buy_items"]=$orderitems;
						if($shopcfg["andor"]!=1){
							return $reda;
						}
					}else{
						$trade_rule[] = "hasitem";
					}
				}
				if($shopcfg["order_pay_time_start"]||$shopcfg["order_pay_time_end"])
				{
					if($resp->trade->pay_time){
						if(strtotime($resp->trade->pay_time)<strtotime($shopcfg["order_pay_time_start"])){
							$reda["hasError"]=true;$reda["status"]=false;
							$reda["score"]="0";
							$reda["giftname"]="亲，只有".$shopcfg["order_pay_time_start"]."之后的订单才可以抽奖哦！";
							if($shopcfg["andor"]!=1){
								return $reda;
							}
						}else{
							$after_start = true;
						}
						if(strtotime($resp->trade->pay_time)>strtotime($shopcfg["order_pay_time_end"])){
							$reda["hasError"]=true;$reda["status"]=false;
							$reda["score"]="0";
							$reda["giftname"]="亲，只有".$shopcfg["order_pay_time_end"]."之前的订单才可以抽奖哦！";
							if($shopcfg["andor"]!=1){
								return $reda;
							}
						}else{
							$befor_end = true;
						}
						if($after_start&&$befor_end){
							$trade_rule[] = "intime";
						}
					}
					if(count($trade_rule)==0&&$shopcfg["andor"]==1){
						$reda["hasError"]=true;$reda["status"]=false;
						$reda["score"]="0";
						$reda["giftname"]="亲，您的订单不满足抽奖条件哦！只有购买了指定商品，或"
										  .$shopcfg["order_pay_time_start"]."-".$shopcfg["order_pay_time_end"]."之间的订单，"
										  ."或".$shopcfg["order_payment"]."元以上的订单才可以抽奖哦！";
						return $reda;
					}
				}
				unset($reda);
				if($topic["status"]<4&&$topic["topic"]==(string)$resp->trade->status)
				{
					$reda["hasError"]=true;$reda["status"]=false;
					$reda["score"]=0;
					switch ((string)$resp->trade->status){
						case "WAIT_BUYER_PAY" :
						$reda["giftname"].="亲，您还没付款哦！请赶紧付款，马上就可以抽奖啦！";
						break;
						case "TRADE_CLOSED" :
						$reda["giftname"].="亲，订单已被关闭哦！不能使用这个订单号，请再拍一件商品吧！";
						break;
						case "TRADE_CLOSED_BY_TAOBAO" :
						$reda["giftname"].="亲，订单已被关闭哦！不能使用这个订单号，请再拍一件商品吧！";
						break;
						case "TRADE_NO_CREATE_PAY" :
						$reda["giftname"].="亲，您还没付款哦！请赶紧付款，马上就可以抽奖啦！";
						break;
						case "PAY_PENDING" :
						$reda["giftname"].="亲，国际信用卡支付正在确认，请稍后再来哦！";
						break;
						case "WAIT_PRE_AUTH_CONFIRM" :
						$reda["giftname"].="亲，0元购合约订单进行中，请交易成功后再来抽奖哦！或者输入其他订单号试试吧！";
						break;
						case "WAIT_BUYER_CONFIRM_GOODS" :
						$reda["giftname"].="亲，我们正在等您确认收货哦！请您确认收货并好评后再来抽奖！";
						break;
						case "WAIT_SELLER_SEND_GOODS" :
						$reda["giftname"].="亲，我们正在为您发货！请您收到货并好评后再来抽奖！";
						break;
						case "SELLER_CONSIGNED_PART" :
						$reda["giftname"].="亲，我们正在为您发货！请您收到货并好评后再来抽奖！";
						break;
						case "TRADE_BUYER_SIGNED" :
						$reda["giftname"].="亲，您已经签收快递，请等待我们收到款以后您就可以抽奖啦！";
						break;
						// case "TRADE_FINISHED" :
						// $reda["giftname"].="亲，交易已成功，请多多购买哦！买的多，抽的多！";
						// break;
					}
					// if(!$resp->trade->buyer_rate&&(string)$resp->trade->status=="TRADE_FINISHED"){
						// $reda["giftname"]="这个订单正在等待您的评价哦！";
					// }
					if($reda["giftname"]){
						$reda["giftname"]="订单状态没有变化哦！<br />".$reda["giftname"];
						return $reda;
					}
				}
					
				unset($reda);
				switch ((string)$resp->trade->status){
					case "WAIT_BUYER_PAY" :
					$reda["giftname"]="亲，您还没付款哦！请赶紧付款，马上就可以抽奖啦！";
					break;
					case "TRADE_CLOSED" :
					$reda["giftname"]="亲，订单已被关闭哦！不能使用这个订单号，请再拍一件商品吧！";
					break;
					case "TRADE_CLOSED_BY_TAOBAO" :
					$reda["giftname"]="亲，订单已被关闭哦！不能使用这个订单号，请再拍一件商品吧！";
					break;
					case "TRADE_NO_CREATE_PAY" :
					$reda["giftname"]="亲，您还没付款哦！请赶紧付款，马上就可以抽奖啦！";
					break;
					case "PAY_PENDING" :
					$reda["giftname"]="亲，国际信用卡支付正在确认，请稍后再来哦！";
					break;
					case "WAIT_PRE_AUTH_CONFIRM" :
					$reda["giftname"]="亲，0元购合约订单进行中，请交易成功后再来抽奖哦！或者输入其他订单号试试吧！";
					break;
					case "TRADE_BUYER_SIGNED" :
					$reda["giftname"].="亲，您已经签收快递，请等待我们收到款以后您就可以抽奖啦！";
					break;
					// case "WAIT_BUYER_CONFIRM_GOODS" :
					// $reda["giftname"]="亲，正在等您确认收货哦！请您确认收货后再来抽奖！";
					// break;
				}
				/*
				$mixed = S("mixed".$resp->trade->buyer_nick); //读取缓存的混淆昵称
				if(!$mixed){
					// 订单中的昵称转化为混淆昵称
					Vendor('taobaosdk.top.request.MixnickGetRequest');
					$this->c->appkey=C("FT_KEY");
					$this->c->secretKey=C("FT_SECRET");
					$req = new \MixnickGetRequest;
					$req->setNick($resp->trade->buyer_nick);
					$mixed = $mre = $this->c->execute($req);
					$mixed = $mixed->nick;
					S("mixed".$resp->trade->buyer_nick,(string)$mixed);
				}

				if($mixed!=$this->mixednick){
					$reda["hasError"]=true;$reda["status"]=false;
					$reda["score"]="0";
					$reda["giftname"]="亲，不是您的订单号哦！".$mixed."|".$this->mixednick . json_encode($mre);
					return $reda;
				}
				//增加一个字段：exchange_byuser，不再判断是否是本人的oid。效果有待观察
				*/
				
				if($reda["giftname"]){
					$reda["hasError"]=true;$reda["status"]=false;
					$reda["score"]=0;
					return $reda;
				}
				
				// 付款后抽奖
				if(((string)$resp->trade->status == "WAIT_SELLER_SEND_GOODS"||(string)$resp->trade->status == "SELLER_CONSIGNED_PART"||(string)$resp->trade->status == "WAIT_BUYER_CONFIRM_GOODS")&&$topic["status"]<2){
					$score_add += ($bei>0)?($shopcfg["order_pay_times"]*$bei):$shopcfg["order_pay_times"];
					$status = 2;
				}
				// 收货后抽奖，要加上付款后抽奖次数
				if((string)$resp->trade->status == "TRADE_FINISHED"&&$topic["status"]<3){
					// if($topic["status"]<2){
						// // 未保存时，为用户直接在完成时抽奖，视为从未抽奖，则应加上付款时的机会
						// // 已保存，应判断是否为付款时抽过奖，如从未抽过则应增加机会，抽过则不给机会
						// $score_add += ($bei>0)?($shopcfg["order_pay_times"]*$bei):$shopcfg["order_pay_times"];
					// }
					$score_add += ($bei>0)?($shopcfg["order_success_times"]*$bei):$shopcfg["order_success_times"];
					$status = 3;
				}
				// 评价后抽奖，要加上前两次
				$rate_level = 0;
				// if($this->readoid&&!$resp->trade->buyer_rate&&$shopcfg["tms_goodrate"]>0){
					// $tmshp = ($bei>0)?($shopcfg["tms_goodrate"]*$bei):$shopcfg["tms_goodrate"];
					// $reda["hasError"]=true;$reda["status"]=false;
					// $reda["score"]="0";
					// $reda["giftname"]="亲，您没有好评哦！不能获得".$tmshp."次好评抽奖机会！请给出好评就可以再抽".$tmshp."次啦！";
					// return $reda;
				// }
				if((string)$resp->trade->buyer_rate=="true" && $shopcfg["tms_goodrate"]>0&&$topic["status"]<4){
						Vendor('taobaosdk.top.request.TraderatesGetRequest');
						$req = new \TraderatesGetRequest;
						$req->setFields("result,content");
						$req->setRateType("give");
						$req->setRole("seller");
						$req->setPageNo(1);
						$req->setPageSize(100);
						$req->setTid($this->oid);
						$rate = $this->c->execute($req, $shopcfg["sessionkey"]);
						// if($rate->code){
							// $reda["hasError"]=true;$reda["status"]=false;
							// $reda["giftname"]="读取评价出错！请联系客服，错误码：<br />".$resp->msg."<br />".$resp->sub_msg;
							// return $reda;
						// }
						
						$badwd = false;
						$content = "";
						$rate_level="";
						foreach($rate->trade_rates->trade_rate as $traderate){
							$rate_level = (string)$traderate->result;
							if($rate_level=="bad"||$rate_level=="neutral"){
								break;
							}
							$content.=(string)$traderate->content;
						}
						
						// if($rate_level!="good"||$rate->total_results==0){
							// $tmshp = ($bei>0)?($shopcfg["tms_goodrate"]*$bei):$shopcfg["tms_goodrate"];
							// $reda["hasError"]=true;$reda["status"]=false;
							// $reda["score"]="0";
							// $reda["giftname"]="亲，您没有好评哦！不能获得".$tmshp."次好评抽奖机会！请给出好评就可以再抽".$tmshp."次啦！注意：追加的不算。";
							// return $reda;
						// }
						
						if($rate_level=="good"){
							$kwds = explode(",",$shopcfg["goodrate_kwd"]);
							foreach($kwds as $kwd){
								if(strpos($content,$kwd)){
									$badwd=true;
								}
							}
						}
						// if($badwd){
							// $reda["hasError"]=true;$reda["status"]=false;
							// $reda["score"]="0";
							// $reda["giftname"]="亲，您给出的评价内容我们无法接受，抱歉您不能抽奖！";
							// return $reda;
						// }
						if($rate_level=="good"&&!$badwd){
							// if($topic["status"]<2&&$status<2){
							// $score_add += ($bei>0)?($shopcfg["order_pay_times"]*$bei):$shopcfg["order_pay_times"];
							// }
							// if($topic["status"]<3&&$status<3){
							// $score_add += ($bei>0)?($shopcfg["order_success_times"]*$bei):$shopcfg["order_success_times"];
							// }
							$score_add += ($bei>0)?($shopcfg["tms_goodrate"]*$bei):$shopcfg["tms_goodrate"];
							$status = 4;
						}
				}
				switch((string)$resp->trade->status){
					case "WAIT_SELLER_SEND_GOODS":$trade_type=1;break;
					case "TRADE_FINISHED":$trade_type=9;break;
					case "WAIT_BUYER_PAY":$trade_type=0;break;
					default:$trade_type=10;break;
				}
				// 存储订单号，不再判断订单类型
				// if((string)$resp->trade->status == "WAIT_SELLER_SEND_GOODS"||(string)$resp->trade->status == "TRADE_FINISHED"||(string)$resp->trade->status == "SELLER_CONSIGNED_PART"){
				if(!$save){
					$data["eid"]=$this->eid;
					$data["exchange"]=$score_add;
					$data["exchange_byuser"]=$this->mixednick;
					$data["sid"]=$this->sid;
					// $data["user_id"]=$shopcfg["taobao_user_id"];
					$data["user_nick"]=(string)$resp->trade->seller_nick;
					$data["buyer_nick"]=(string)$resp->trade->buyer_nick;
					$data["payment"]=(float)$resp->trade->payment;
					$data["oid"]=$this->oid;
					$data["tid"]=$this->oid;
					$data["type"]='';
					$data["pub_time"]=$resp->trade->pay_time?date("Y-m-d H:i:s",strtotime($resp->trade->pay_time)):date("Y-m-d H:i:s");
					$data["topic"]=(string)$resp->trade->status;
					$data["trade_type"]=$trade_type;
					$data["rate_level"]=$rate_level;
					$data["ts"]=date("Y-m-d H:i:s");
					$data["status"]=$status;
					$Order->add($data);
					//增加一个被谁兑换的字段，可以不再判断是否是本人的oid
				}else{
					$data["status"]=$status;
					$data["topic"]=(string)$resp->trade->status;
					$data["trade_type"]=$trade_type;
					$data["rate_level"]=$rate_level;
					$data["exchange"]= array('exp','exchange+'.$score_add);
					$Order->where(Array("oid"=>$this->oid))->save($data);
				}
				if($score_add>0){
					// 已经兑换到，更新记录
					$EU = M("EventsUsers");
					$euw=Array("sid"=>$this->sid,"eventid"=>$this->eid,"uzuid"=>$this->shop_uid);
					$re = $EU->where($euw)->setInc("score",$score_add);
					$this->hasError = !$re;
					$this->get_score = $score_add;
					$this->msg = "成功兑换 $score_add 次抽奖机会！";
				}
				unset($data);
	}
	private function getEveryday(){
		$EV = M("Events");
		$EU = M("EventsUsers");
		$euw=Array("sid"=>$this->sid,"eventid"=>$this->eid,"uzuid"=>$this->shop_uid);
		$add = $EU->where($euw)->getField("addtime");
		
		if(date("Ymd",strtotime($add))!=date("Ymd")){
			$tms = $EV->where(Array("id"=>$this->eid,"sid"=>$this->sid))->getField("tms_everyday");
			$this->hasError=false;
		}else{
			$this->hasError=true;
			$this->msg="每天只能获取一次抽奖机会。请隔一天再来领取";
			return;
		}
		
		if($tms>0){
			$data["addtime"] = date("Y-m-d H:i:s");
			$data["score"] = array('exp','score+'.$tms);
			$re = $EU->where($euw)->save($data);
			if($re){
				$this->hasError=false;
				$this->msg="您已成功获取 $tms 次机会！";
			}else{
				$this->hasError=true;
				$this->msg="获取每天赠送的次数出错";
			}
		}else{
			$this->hasError=true;
			$this->msg="今天可获取的次数为0";
		}
	}
}